package com.mingqijia.gassafety.shared.vcc;

import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.gap.basic.base.CommonResponse;
import com.mingqijia.gassafety.shared.request.VccAccountNumberListRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
@RequiredArgsConstructor
public class VccSystemProvider {

//    private static final String URL_ORG_INFO = "%s/open-business-normal/bridge/mv1/uum/org/orgs/all?stdCode=%s&updateTime=%s&pageIndex=%s&pageSize=%s&%s";

    /*============================================组织管理==========================================*/
    /**
     * 根据用户id查询角色下的部门id  get
     */
    private static final String ORG_DEPART_IDS = "%s/uum/user/authority/orgByUserId?userId=%s&spId=%s";

    /**
     * 根据spid查询所有部门id   post
     */
    private static final String ORG_DEPART_LIST = "%s/uum/user/authority/orgBySpId";

    /**
     * 新增编辑校验 post
     */
    private static final String ORG_DEPART_CHECK = "%s/uum/user/authority/queryOrgByUserSpId?userId=%s&spId=%s";
    /**
     * 新增组织 post
     */
    private static final String ORG_DEPART_ADD = "%s/uum/user/authority/addOrg";
    /**
     * 编辑组织 post
     */
    private static final String ORG_DEPART_EDIT = "%s/uum/user/authority/updateOrg";
    /**
     * 根据组织id查询当前组织信息 get
     */
    private static final String ORG_DEPART_DETAIL = "%s/uum/user/authority/getOrgByOrgId?orgId=%s";

    /**
     * 根据spId查询当前企业组织类型字典 get
     */
    private static final String ORG_DEPART_TYPE_LIST = "%s/uum/user/authority/queryOrgBySpId?spId=%s&dictCode=%s";

    /*============================================账号管理==========================================*/


    /**
     * 账号列表
     */
    private static final String ACCOUNT_NUMBER_LIST = "%s/uum/user/authority/userinfoCompQuery";

    /**
     * 新增账号
     */
    private static final String ACCOUNT_NUMBER_ADD = "%s/uum/user/authority/userinfoCompAdd";

    /**
     *  编辑账号
     */
    private static final String ACCOUNT_NUMBER_EDIT = "%s/uum/user/authority/userinfoCompUpdate";

    private static final String ACCOUNT_NUMBER_DETAIL = "%s/uum/user/authority/userinfoCompGet?id=%s&spId=%s&userId=%s";

    private static final String ACCOUNT_NUMBER_UPDATE_STATUS = "%s/uum/user/authority/userinfoCompLock";
    private static final String ACCOUNT_NUMBER_BATCH_UPDATE_STATUS = "%s/uum/user/authority/userinfoCompBatchLock";
    private static final String ACCOUNT_NUMBER_RESET_PASSWORD = "%s/uum/user/authority/userinfoCompReset";

    private static final String ACCOUNT_NUMBER_ROLE_LIST = "%s/uum/user/authority/sp?spId=%s";

    /**
     * 校验手机号是否重复
     */
    private static final String ACCOUNT_NUMBER_CHECK_MOBILE = "%s/uum/user/authority/checkMobileNosp?mobile=%s&spId=%s";
    /**
     * 校验员工号是否重复
     */
    private static final String ACCOUNT_NUMBER_CHECK_STAFF_CODE = "%s/uum/user/authority/checkStaffCode?staffCode=%s&spId=%s";
    private static final String ACCOUNT_NUMBER_CHECK_USER_CODE = "%s/uum/user/users/nosp?userCode=%s";
    //校验密码是否符合规则
    private static final String ACCOUNT_NUMBER_CHECK_PASSWORD = "%s/uum/user/authority/checkPassword?password=%s&spId=%s";
    //根据规则生成密码
    private static final String ACCOUNT_NUMBER_GENPASSWORD = "%s/uum/user/authority/genPassword?spId=%s";
    //查询密码规则 若没有，取集团
    private static final String ACCOUNT_NUMBER_QUERYPWDCONFIG = "%s/uum/user/authority/queryPwdConfig?spId=%s";




    public String org_depart_ids(String id,String spId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.GET, String.format(ORG_DEPART_IDS, url, id, spId));

        log.info("根据条件，参数查询org_depart_ids:{}", id);
        return doHttpEwtRequest(request);
    }



    public String org_depart_list(String spId,String orgName,List<String> ids, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.POST, String.format(ORG_DEPART_LIST, url));

        Map<String, Object> params = new HashMap<String, Object>() {{
            put("spId", spId);
        }};
        if (StringUtils.isNotEmpty(orgName)) params.put("orgName", orgName);
        if (CollectionUtils.isNotEmpty(ids)) params.put("orgIds", ids);

        log.info("根据条件，参数查询org_depart_list:{}", JSONUtil.toJsonStr(params));
        request.body(JSONUtil.toJsonStr(params), ContentType.JSON.getValue());
        return doHttpEwtRequest(request);
    }

    public String org_depart_check(String userId, String spId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.GET, String.format(ORG_DEPART_CHECK, url, userId, spId));

        log.info("根据条件，参数新增org_depart_add:{},{}", userId, spId);
        return doHttpEwtRequest(request);
    }

    public String org_depart_add(String spId,String orgName,String pId,String orgType,Integer displayOrder,String userId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.POST, String.format(ORG_DEPART_ADD, url));

        Map<String, Object> params = new HashMap<String, Object>() {{
            put("spId", spId);
            put("orgName", orgName);
            put("pId", pId);
            put("userId", userId);
            put("orgType", orgType);
            put("displayOrder", displayOrder);
        }};

        log.info("根据条件，参数新增org_depart_add:{}", JSONUtil.toJsonStr(params));
        request.body(JSONUtil.toJsonStr(params), ContentType.JSON.getValue());
        return doHttpEwtRequest(request);
    }

    public String org_depart_edit(String id,String spId,String orgName,String pId,String orgType,Integer displayOrder,String userId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.POST, String.format(ORG_DEPART_EDIT, url));

        Map<String, Object> params = new HashMap<String, Object>() {{
            put("id", id);
            put("spId", spId);
            put("orgName", orgName);
            put("pId", pId);
            put("userId", userId);
            put("orgType", orgType);
            put("displayOrder", displayOrder);
        }};

        log.info("根据条件，参数编辑org_depart_edit:{}", JSONUtil.toJsonStr(params));
        request.body(JSONUtil.toJsonStr(params), ContentType.JSON.getValue());
        return doHttpEwtRequest(request);
    }

    public String org_depart_detail(String id, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.GET, String.format(ORG_DEPART_DETAIL, url, id));

        log.info("根据条件，参数新增org_depart_add:{}", id);
        return doHttpEwtRequest(request);
    }

    public String org_depart_type_list(String dictCode ,String id, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.GET, String.format(ORG_DEPART_TYPE_LIST, url, id,dictCode));

        log.info("根据条件，参数查询org_depart_type_list:{}", id);
        return doHttpEwtRequest(request);
    }

    /*============================================账号管理==========================================*/
    public CommonResponse<String> account_number_list(VccAccountNumberListRequest req,String spId, String userId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.POST, String.format(ACCOUNT_NUMBER_LIST, url));

        Map<String, Object> params = new HashMap<String, Object>() {{
            put("pageIndex", req.getPageIndex());
            put("pageSize", req.getPageSize());
            put("spId", spId);
            put("orgId", req.getOrgId());
            put("userId", userId);
        }};
        if (StringUtils.isNotEmpty(req.getUserName())) params.put("userName", req.getUserName()); //用户名
        if (StringUtils.isNotEmpty(req.getUserCode())) params.put("userCode", req.getUserCode()); //用户账号
        if (StringUtils.isNotEmpty(req.getState())) params.put("state", req.getState()); //状态
        if (StringUtils.isNotEmpty(req.getContactInfo())) params.put("contactInfo", req.getContactInfo()); //用户手机号
        if (CollectionUtils.isNotEmpty(req.getRoleIds())) params.put("roleIds", req.getRoleIds()); //角色id
        if (CollectionUtils.isNotEmpty(req.getStaffInfo())) params.put("staffInfo", req.getStaffInfo()); //员工id

        log.info("根据条件，参数账号列表account_number_list:{}", JSONUtil.toJsonStr(params));
        request.body(JSONUtil.toJsonStr(params), ContentType.JSON.getValue());
        return doHttpEwtRequest2(request);
    }

    public CommonResponse<String> account_number_add(VccAccountNumberListRequest req,String spId, String userId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.POST, String.format(ACCOUNT_NUMBER_ADD, url));

        Map<String, Object> params = new HashMap<String, Object>() {{
            put("staffCode", req.getStaffCode());
            put("userName", req.getUserName());
            put("userCode", req.getUserCode());
            put("password", req.getPassword());
            put("spId", spId);
            put("orgIds", new ArrayList<>(Collections.singleton(req.getOrgId())));
            put("contactInfo", req.getContactInfo());
            put("userId", userId);
        }};

        if (CollectionUtils.isNotEmpty(req.getRoleIds())) params.put("roleIds", req.getRoleIds()); //角色id
        if (StringUtils.isNotEmpty(req.getComments())) params.put("comments", req.getComments()); //用户账号

        log.info("根据条件,新增账号参数account_number_add:{}", JSONUtil.toJsonStr(params));
        request.body(JSONUtil.toJsonStr(params), ContentType.JSON.getValue());
        return doHttpEwtRequest2(request);
    }

    public CommonResponse<String> account_number_edit(VccAccountNumberListRequest req,String id,String spId, String userId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.POST, String.format(ACCOUNT_NUMBER_EDIT, url));

        Map<String, Object> params = new HashMap<String, Object>() {{
            put("staffCode", req.getStaffCode());
            put("userName", req.getUserName());
            put("userCode", req.getUserCode());
            put("spId", spId);
            put("orgIds", req.getOrgId());
            put("contactInfo", req.getContactInfo());
            put("userId", userId);
            put("afterStaffId", req.getStaffId());
            put("id", id);
        }};

        if (CollectionUtils.isNotEmpty(req.getRoleIds())) params.put("roleIds", req.getRoleIds()); //角色id
        if (StringUtils.isNotEmpty(req.getComments())) params.put("comments", req.getComments()); //用户账号

        log.info("根据条件，编辑账号参数account_number_edit:{}", JSONUtil.toJsonStr(params));
        request.body(JSONUtil.toJsonStr(params), ContentType.JSON.getValue());
        return doHttpEwtRequest2(request);
    }


    public CommonResponse<String> account_number_detail(String id ,String spId, String userId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.GET, String.format(ACCOUNT_NUMBER_DETAIL, url,id,spId,userId));

        log.info("根据条件，查详情:{}", id);
        return doHttpEwtRequest2(request);
    }

    public CommonResponse<String> account_number_update_status(String id,String state,String spId, String userId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.POST, String.format(ACCOUNT_NUMBER_UPDATE_STATUS, url));

        Map<String, Object> params = new HashMap<String, Object>() {{
            put("spId", spId);
            put("state",state);
            put("userId",userId);
            put("id",id);
        }};

        log.info("根据条件，更新账号状态:{}", JSONUtil.toJsonStr(params));
        request.body(JSONUtil.toJsonStr(params), ContentType.JSON.getValue());
        return doHttpEwtRequest2(request);
    }
    public CommonResponse<String> account_number_batch_update_status(List<String> ids,String state,String spId, String userId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.POST, String.format(ACCOUNT_NUMBER_BATCH_UPDATE_STATUS, url));

        Map<String, Object> params = new HashMap<String, Object>() {{
            put("spId", spId);
            put("state",state);
            put("userId",userId);
            put("ids",ids);
        }};

        log.info("根据条件，批量更新账号状态:{}", JSONUtil.toJsonStr(params));
        request.body(JSONUtil.toJsonStr(params), ContentType.JSON.getValue());
        return doHttpEwtRequest2(request);
    }

    public CommonResponse<String> account_number_reset_password(String state,String id,String spId, String userId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.POST, String.format(ACCOUNT_NUMBER_RESET_PASSWORD, url));
        Map<String, Object> params = new HashMap<String, Object>() {{
            put("spId", spId);
            put("id", id);
            put("userId", userId);
            put("state", state);
        }};

        log.info("根据条件，重置密码:{}", JSONUtil.toJsonStr(params));
        request.body(JSONUtil.toJsonStr(params), ContentType.JSON.getValue());
        return doHttpEwtRequest2(request);
    }

    public CommonResponse<String> account_number_role_list(String spId, String userId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.GET, String.format(ACCOUNT_NUMBER_ROLE_LIST, url,spId));

        log.info("根据条件，角色列表:{}", spId);
        return doHttpEwtRequest2(request);
    }
    public CommonResponse<String> account_number_check_mobile(String spId, String userId, String mobile,  String url) {
        HttpRequest request = HttpUtil.createRequest(Method.GET, String.format(ACCOUNT_NUMBER_CHECK_MOBILE, url,mobile,spId));
        log.info("根据条件，校验手机号:{}", mobile);

        return doHttpEwtRequest2(request);
    }

    public CommonResponse<String> account_number_check_staff_code(String spId, String userId, String staffCode,  String url) {
        HttpRequest request = HttpUtil.createRequest(Method.GET, String.format(ACCOUNT_NUMBER_CHECK_STAFF_CODE, url,staffCode,spId));
        log.info("根据条件，校验员工工号:{}", staffCode);

        return doHttpEwtRequest2(request);
    }
    public CommonResponse<String> account_number_check_user_code(String spId, String userId, String userCode,  String url) {
        HttpRequest request = HttpUtil.createRequest(Method.GET, String.format(ACCOUNT_NUMBER_CHECK_USER_CODE, url,userCode));
        log.info("根据条件，校验账号:{}", userCode);

        return doHttpEwtRequest2(request);
    }

    public CommonResponse<String> accountCheckPassword(String spId,String password,  String url) {
        HttpRequest request = HttpUtil.createRequest(Method.GET, String.format(ACCOUNT_NUMBER_CHECK_PASSWORD, url, password, spId));
        log.info("根据条件，校验账号:{}", password);

        return doHttpEwtRequest2(request);
    }

    public CommonResponse<String> accountGenPassword(String spId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.GET, String.format(ACCOUNT_NUMBER_GENPASSWORD, url, spId));
        log.info("根据条件，生成密码:{}", spId);

        return doHttpEwtRequest2(request);
    }

    public CommonResponse<String> accountQueryPwdConfig(String spId, String url) {
        HttpRequest request = HttpUtil.createRequest(Method.GET, String.format(ACCOUNT_NUMBER_QUERYPWDCONFIG, url, spId));
        log.info("根据条件，查询密码规则:{}", spId);

        return doHttpEwtRequest2(request);
    }



    private String doHttpEwtRequest(HttpRequest request) {
        HttpResponse response = request.execute();
        log.info("doHttpRequest：{}", com.alibaba.fastjson.JSONObject.toJSONString(response));
        if (!Objects.equals(response.getStatus(), HttpStatus.HTTP_OK)) {
            log.error("调用{}失败, 返回：{}", request.getUrl(), response.body());
            return null;
        }
        log.info("调用{}, 返回:{}", request.getUrl(), response.body());
        return response.body();
    }

    private CommonResponse<String> doHttpEwtRequest2(HttpRequest request) {
        HttpResponse response = request.execute();
        log.info("doHttpRequest：{}", com.alibaba.fastjson.JSONObject.toJSONString(response));
        if (!Objects.equals(response.getStatus(), HttpStatus.HTTP_OK)) {
            log.error("调用{}失败, 返回：{}", request.getUrl(), response.body());
            Integer error_code =  JSONObject.parseObject(response.body()).getInteger("error_code");
            String error_message =  JSONObject.parseObject(response.body()).getString("error_message");
            if (null != error_code && error_code > 0) {
                return CommonResponse.failure(error_code, error_message);
            }
            return CommonResponse.failure(-1, "系统错误");
        }
        log.info("调用{}, 返回:{}", request.getUrl(), response.body());
        return CommonResponse.success(response.body());
    }
}
